package cn.kgc.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.kgc.entity.Roles;
import cn.kgc.entity.RolesMenus;
import cn.kgc.mapper.RolesMapper;
import cn.kgc.service.RolesMenusService;
import cn.kgc.service.RolesService;
import cn.kgc.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author YC
 */
@Slf4j
@Service("rolesService")
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {

    @Resource
    private RolesMenusService rolesMenusService;
    @Resource
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRolesById(Integer id) {
        // 根据角色删除角色表信息
        boolean roleResult = removeById(id);
        // 以及对应的角色菜单表的信息
        LambdaQueryWrapper<RolesMenus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolesMenus::getRid, id);
        boolean roleMenusResult = rolesMenusService.remove(wrapper);
        return roleResult && roleMenusResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRolesMenus(Map<String, Object> map) {
        // 根据角色删除角色表信息
        int roleId = MapUtil.getInt(map, "roleId");
        LambdaQueryWrapper<RolesMenus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolesMenus::getRid, roleId);
        boolean roleMenusResult = rolesMenusService.remove(wrapper);
        // 新增更新的角色拥有的菜单
        List<Integer> menuIds = (List<Integer>) map.get("menusId");
        List<RolesMenus> rolesMenusList = menuIds.stream().map(menuId -> {
            return RolesMenus.builder().rid(roleId).mid(menuId).build();
        }).collect(Collectors.toList());
        boolean saveBatchResult = rolesMenusService.saveBatch(rolesMenusList);
        // 删除缓存
        redisUtil.delete("'system:authorities:'" + map.get("roleId"));
        return roleMenusResult && saveBatchResult;
    }

}
